import os
import pickle
import numpy as np
import h5py
import random
import math

from Config.Config import DPN107_FEATURE_PATH
from Config.Config import DPN107_RGB_200_PATH

from functools import lru_cache

@lru_cache(maxsize=1000)
def load_DPN107_from_file(vid):
    try:
        with h5py.File(os.path.join(DPN107_RGB_200_PATH,'{}.h5'.format(vid)),'r') as f:
            d = f['feature201'][:]
            return d
    except Exception as E:
        raise E

def extract_DPN107_from_proposal(feat, num_frame, duration, start, end, K, zero_padding=False, repeat=True):

    # K 大于 len 时如果 repeat=False 则取出全部的帧

    fps = num_frame / duration
    numfeat = feat.shape[0]
    indexes = np.asarray(np.arange(numfeat))

    # 特征长度和视频的长度对不上!!!
    startframe = round(start*fps)/round(fps*0.4)
    endframe = round(end*fps)/round(fps*0.4)

    #get in range indexes
    inrange = np.nonzero([np.logical_and(indexes<=endframe, indexes>=startframe)])[1]

    if len(inrange)==0: return None

    # 不管怎么样采了selected帧
    # TODO what's this?
    start_out = max(0-start,0)
    end_out = max(end-duration,0)

    if (start_out+end_out)>0 and zero_padding:
        start_zeros = int(round(start_out*K/(end-start)))
        end_zeros = int(round(end_out*K/(end-start)))

        nselect = K-start_zeros-end_zeros
        if len(inrange)<nselect and not repeat:
            selected = inrange
        else:
            inds = np.floor(np.arange(0,len(inrange)-1e-6,float(len(inrange))/nselect)+float(len(inrange))/(2*nselect)).astype(int)
            selected = inrange[inds]

        data = np.vstack((np.zeros((start_zeros, feat.shape[1])), feat[selected,:], np.zeros((end_zeros, feat.shape[1]))))
    else:
        if len(inrange)<K and not repeat:
            selected = inrange
        else:
            inds = np.floor(np.arange(0,len(inrange)-1e-6,float(len(inrange))/K)+float(len(inrange))/(2*K)).astype(int)
            selected = inrange[inds]

        data = feat[selected,:]
    #
    # print('EXTRACT_tsnSCORE_FROM_PROPOSAL:')
    # print('feat_shape:',feat.shape)
    # print('num_frame:',num_frame)
    # print('duration:',duration)
    # print('start:',start,' end:',end)
    # print('K:',K)
    # print('zero_pad',zero_padding,' repeat',repeat)
    # print('fps:',fps)
    # print('starteframe:',startframe,'endframe:',endframe)
    # print('start_out:',start_out,'end_out:',end_out)
    # condition = ((start_out+end_out)>0 and zero_padding)
    # print('IF Condition',condition)
    # if condition:
    #     print('start_zeros:',start_zeros,' end_zeros:',end_zeros)
    #     print('nselect:',nselect)
    # import IPython;IPython.embed()

    return data


def extract_DPN107_feature(feature, proposal, num_frame, duration, PYRAMID=[12,12],SpliteData=False,**kwargs):
    # 抽取特征
    data = []
    for ind, num in enumerate(PYRAMID):
        feat = extract_DPN107_from_proposal(feature, num_frame, duration, proposal[ind,0], proposal[ind,1], num, zero_padding=True, **kwargs)
        if feat is None: return None
        data.append(feat)
    if SpliteData == False: return np.vstack(data)
    elif SpliteData == True: return data

def test1():
    vid = '_kG3DxvGnnQ'
    feat = load_DPN107_from_file(vid)

if __name__=='__main__':
    vid = 'Zxi0V2pBPlA'
    feat = load_DPN107_from_file(vid)

